/**
单独打开编辑页的url：http://host:port/StoreAdmin/product/prod.html?doAction=edit&productId={id}
单独打开新增页的url：http://host:port/StoreAdmin/product/prod.html?doAction=edit&productTypeId={id}
**/

$j(document).ready(function () {
	$j('#divDlgoptionValueChoies').remove(); //必须先清空规格选择dialog的内容，因为会dialog会残留。
});



//自动以的setTimeout方法，可传递参数
function masterSetTimeout(callback,timeout,param)
{
    var args = Array.prototype.slice.call(arguments,2);
    var _cb = function()
    {
        callback.apply(null,args);
    }  
    window.setTimeout(_cb,timeout);
}


function displayButtons(status){
	disableIconBtn("save");
	disableIconBtn("saveAndReturn");
	disableIconBtn("saveAndAddSimilar");
	disableIconBtn("delete");
	if(status == null){
		//case: 新增
		enableIconBtn("save");
		enableIconBtn("saveAndReturn");
		enableIconBtn("saveAndAddSimilar");
		disableIconBtn("delete");
	}else if(status == 1){
		//case:激活
		enableIconBtn("save");
		enableIconBtn("saveAndReturn");
		enableIconBtn("saveAndAddSimilar");
		enableIconBtn("delete");
	}else if(status == 0){
		//case:不激活
		enableIconBtn("save");
		enableIconBtn("saveAndReturn");
		enableIconBtn("saveAndAddSimilar");
		enableIconBtn("delete");
	}else if(status == -1){
		//case:逻辑删除
		disableIconBtn("save");
		disableIconBtn("saveAndReturn");
		disableIconBtn("saveAndAddSimilar");
		disableIconBtn("delete");
	}
}	

String.prototype.trim= function(){  
   	// 用正则表达式将前后空格  
   	// 用空字符串替代。  
   	return this.replace(/(^\s*)|(\s*$)/g, "");  
}
var mediaId = 0; //media计数器
var skuCounter=0; //sku计数器
var wholesalePriceCounter=0;  //批发价计数器 
var problemQuantity;  //问题所在的quantity 对象类型
//存储规格数组，规格JSON格式为{id,name}
var skuOptionArray = new Array();
//存储规格值二维数组，JSON格式为{id,name,value,type}
//skuOptionValueArray[i][j] 表示第i个规格的第j个规格值，排序由sortOrder决定
var skuOptionValueArray = new Array();
//用于存放目前已关联的规格id拼接字符串
var optionIds; 
var recommendedProductCounter = 0;//推荐商品计数器
var currentTypeId; //记录当前的推荐类型
var currentMiddleImageId;  //记录当前中图是哪个小图点击而打开的
var weightUnit = "g";  //重量单位
var isLoadImagesSuccess = false; 
var isLoadSkusSuccess = false; 
var isLoadAttributesSuccess = false; 
var isLoadRecommendsSuccess = false; 
var productStatus = -1;

//初始化验证
function initValidate(){
	applyValidate($j("#description").get(0),"maxlength=30000");
	applyValidate($j("#shortDescription").get(0),"maxlength=250");
	applyValidate($j('#categoryId').get(0),"required");
	
}
function initVariables(){
	mediaId = 0;
	skuCounter=0;
	wholesalePriceCounter=0; 
	problemQuantity = null;
	skuOptionArray = new Array();
	skuOptionValueArray = new Array();
	optionIds = "";
	recommendedProductCounter = 0;
	currentTypeId ="";
	currentMiddleImageId = ""; 
	isLoadImagesSuccess = false; 
	isLoadSkusSuccess = false; 
	isLoadAttributesSuccess = false; 
	isLoadRecommendsSuccess = false; 
	productStatus = -1;
}

function initVariablesForAddSimilar(){
	mediaId = 0;
	skuCounter=0;
	wholesalePriceCounter=0; 
	problemQuantity = null;
	recommendedProductCounter = 0;
	currentTypeId ="";
}

//增加商品图片  media是一个JSON对象{mediaId,mediaDescription,mediaUrl},needMoveIcons用于是否执行函数showImageMoveIcons，用于页面速度优化，默认需要
function addNewProductImage(media,needMoveIcons){
	
	var id,mediaUrl,src_s0,src_m0,desc;
	//stat : set id,src
	
	id = "_"+media.mediaId;
	mediaUrl = media.mediaUrl;
	src_s0 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s0"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	src_m0 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_m0"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	desc = media.mediaDescription;
	//end:
	
	var html = '';
	html += '<td class="productImageDiv" id="image'+id+'">';
	html += '<div  class="img clearfix"><a href="javascript:void(0)" onclick="showBigPict(\'mediaImage'+id+'\')">';
	html += '<img id="mediaImage'+id+'"  src="' + src_s0+ '" src_m0="'+src_m0+'" mediaUrl="'+__mediaPath+mediaUrl+'" width="50" height="50" onerror="this.src=__defaultImage;this.onerror=\'\'" /></a>';
	html += '<div class="do">';
	html += '<a href="javascript:void(0)" name="move_l" class="move_l" onclick="moveUpProductImage(this)">up</a>';
	html += '<a href="javascript:void(0)" name="del" class="del" onclick="removeProductImage(this)">delete</a>';
	html += '<a href="javascript:void(0)" name="move_r" class="move_r" onclick="moveDownProductImage(this)">down</a>';
	html += '</div></div>';
	
	//start: hidden
	html += '<input type="hidden" name="mediaUrls" value="'+media.mediaUrl+'" id="mediaUrl'+id+'"  />';
	html += '<input type="hidden" name="mediaIds" id="mediaId'+id+'" value="mediaId'+id+'"/>';
	html += '<input type="hidden" name="mediaTypes" value="0"/>';
	html += '<input type="hidden" name="mediaDescs" value=""/>';
	//end : hidden
	html += '</td>';
	
	$j('#imageList').append(html);
	$j('#image'+id).hover(
		function(){
			$j(this).find('.do').show();
		},
		function(){
			$j(this).find('.do').hide();
		}
	);
	$j('#allPicsDiv').show();
	if(needMoveIcons == null || needMoveIcons){
		showImageMoveIcons();
	}	
	
	//如果是上传的第一幅图,则显示在主图区域
	if($j('#imageList td').length==1){
		showBigPict('mediaImage'+id);
	}
	
}

//在主图区域显示图片
function showBigPict(mediaImageId){
	$j('#productMainImageDiv').get(0).src = $j('#'+mediaImageId).attr("src_m0");
	$j("#productMainImageDiv").parent('a').attr("href",$j('#'+mediaImageId).attr("mediaUrl")).attr("target","_blank");
	currentMiddleImageId = $j('#'+mediaImageId).parents(".productImageDiv").attr("id");

}

//上传商品图片后的回调函数
function uploadProductImagehandler(mediaUrl,fileInputId){
	mediaId++;
	addNewProductImage({"mediaId":'new_'+mediaId,"mediaDescription":"","mediaUrl":mediaUrl});
}

//刷新图片区左移和右移图标是否显示
function showImageMoveIcons(){
	$j('#imageList td.productImageDiv a[name="move_l"]').addClass("move_l").removeClass("move_l_gray");
	$j('#imageList td.productImageDiv a[name="move_r"]').addClass("move_r").removeClass("move_r_gray");
	$j('#imageList td.productImageDiv:first a[name="move_l"]').addClass("move_l_gray").removeClass("move_l");
	$j('#imageList td.productImageDiv:last a[name="move_r"]').addClass("move_r_gray").removeClass("move_r");
	
}

//删除所有图片
function removeAllProductImage(){
	if (confirm(__FMT.productForm_deleteAllImage_confirm +"?")) {
		$j(".productImageDiv").remove();
		$j('#productMainImageDiv').get(0).src = __defaultImage_m0;
		$j("#productMainImageDiv").parent('a').attr("href","javascript:void(0)").attr("target","");
	}
}

//删除图片 
//linkDOM 是一个超链接对象
function removeProductImage(linkDOM){
	if (confirm(__FMT.common_message_confirmDeleteThis +"?")) {
		var jProductImage = $j(linkDOM).parents(".productImageDiv");
		if(jProductImage.attr("id") == currentMiddleImageId){
			//如果删除的小图是当前中图所放大的
			var jProductImageNextDisplay =  jProductImage.next();
			if(jProductImageNextDisplay.length==0){
				jProductImageNextDisplay = jProductImage.prev();
			}
			if(jProductImageNextDisplay.length==0){
				//如果已经没有任何图片
				$j('#productMainImageDiv').get(0).src = __defaultImage_m0;
				$j("#productMainImageDiv").parent('a').attr("href","javascript:void(0)").attr("target","");
			}else{
				//删除的图片之后或之前还有图片
				showBigPict(jProductImageNextDisplay.find('img[src_m0]').attr("id"));
			}
		}
		jProductImage.remove();
		
		showImageMoveIcons();
	}
}

//提升图片顺序
//linkDOM 是一个超链接对象
function moveUpProductImage(linkDOM){
	var me = $j(linkDOM).parents(".productImageDiv");
	var prev = me.prev(".productImageDiv");
	prev.before(me);
	showImageMoveIcons();
}
//降低图片顺序
//linkDOM 是一个超链接对象
function moveDownProductImage(linkDOM){
	var me = $j(linkDOM).parents(".productImageDiv");
	var next = me.next(".productImageDiv");
	next.after(me);
	showImageMoveIcons();
}


//增加附件  media是一个JSON对象{mediaId,mediaDescription,mediaUrl} needMoveIcons用于是否执行函数showAccessoryMoveIcons，用于页面速度优化，默认需要
function addNewProductAccessory(media,needMoveIcons){
	var id,src,desc;
	//stat : set id,src
	
	id = "_"+media.mediaId;
	src = __ctxPath + '/product/prod.html?doAction=downloadFile&mediaUrl='+ media.mediaUrl;
	desc = media.mediaDescription;
	
	name = src.substring(src.lastIndexOf("/")+1);
	//end:
	
	var html = '';
	html += '<tr class="productAccesssoryDiv">';
	html += '<td><a href="'+src+'" target="_blank">'+name+'</td>';
	html += '<td><a class="up" href="javascript:void(0)" onclick="moveUpProductAccessory(this)" name="move_up"></a>';
	html += '<a class="down" href="javascript:void(0)" onclick="moveDownProductAccessory(this)" name="move_down"></a>';
	html += '<a class="del" href="javascript:void(0)" onclick="removeProductAccessory(this)"></a></td>';
	html += '<td><input class="inputtxt" type="text" style="width: 160px;" id="mediaDesc'+id+'" name="mediaDescs" value="'+desc+'" title="'+__FMT.productForm_media_title_tip+'"/></td>';
	html += '<td></td>';
	
	//start: hidden
	html += '<input type="hidden" name="mediaIds" id="mediaId'+id+'" value="mediaId'+id+'"/>';
	html += '<input type="hidden" name="mediaTypes" value="1"/>';
	html += '<input type="hidden" name="mediaUrls" value="'+((media!=null)?media.mediaUrl:'')+'" id="mediaUrl'+id+'"  />';
	//end : hidden
	
	html += '</tr>';
	$j('#accessoryList').append(html);
	if(needMoveIcons == null || needMoveIcons){
		showAccessoryMoveIcons();
	}		
}

//上传商品附件后的回调函数
function uploadProductAccessoryhandler(mediaUrl,fileInputId){
	mediaId++;
	addNewProductAccessory({"mediaId":'new_'+mediaId,"mediaDescription":"","mediaUrl":mediaUrl});
}
//删除附件 
//linkDOM 是一个超链接对象
function removeProductAccessory(linkDOM){
	$j(linkDOM).parents(".productAccesssoryDiv").remove();
	showAccessoryMoveIcons();
}

//提升附件顺序
//linkDOM 是一个超链接对象
function moveUpProductAccessory(linkDOM){
	var me = $j(linkDOM).parents(".productAccesssoryDiv");
	var prev = me.prev(".productAccesssoryDiv");
	prev.before(me);
	showAccessoryMoveIcons();
}

//降低附件顺序
//linkDOM 是一个超链接对象
function moveDownProductAccessory(linkDOM){
	var me = $j(linkDOM).parents(".productAccesssoryDiv");
	var next = me.next(".productAccesssoryDiv");
	next.after(me);
	showAccessoryMoveIcons();
}

//刷新附件上下移动按钮显示
function showAccessoryMoveIcons(){
	$j('#accessoryList tr.productAccesssoryDiv a[name="move_up"]').addClass("up").removeClass("up_gray");
	$j('#accessoryList tr.productAccesssoryDiv a[name="move_down"]').addClass("down").removeClass("down_gray");
	$j('#accessoryList tr.productAccesssoryDiv:first a[name="move_up"]').addClass("up_gray").removeClass("up");
	$j('#accessoryList tr.productAccesssoryDiv:last a[name="move_down"]').addClass("down_gray").removeClass("down");
}


//验证函数
function validateAction(){	

	var flag = true;
	
	//start:validate apply
	
	//=======begin:验证更新的库存与已售库存大小================
	var intRang = "intRange=[0-100000]";
	$j("#skuTable").find("table[class='normal_table1']").each(function(ic, ot){
		$j(ot).find("input[name='inventorys']").each(function(i, o){
			var currInven = $j(o).val();
			var alloinven = $j(o).parent("td").find("input[name='inventory_allocatedQ']").val();
			$j(o).parent("td").find("img").remove();
			if (currInven && alloinven && currInven!="" && alloinven!="" && parseInt(currInven)<parseInt(alloinven)) {//当前库存小于已分配库存
				var valQuantiry = intRang + ",minValue=" + alloinven;
				applyValidate(o,valQuantiry);
				//定位
				var trid = $j(o).attr("id")+"td";
				$j(o).parent("td").attr("id",trid);
				window.location.href="#"+trid;
			} else {
				var valQuantiry = intRang;
				applyValidate(o,valQuantiry);
			}
		});
	});
	//=======end:验证更新的库存与已售库存大小================
	
	
	$j('input[name="mediaDescs"]').each(function(index,obj){
		applyValidate(obj,"maxlength=25");
	});
	var jSkuCodes= $j('input[name="skuCodes"]');
	if(jSkuCodes.size()!=1){
		jSkuCodes.each(function(index,obj){
			applyValidate(obj,"maxlength=15");
		});
	}else{
		jSkuCodes.each(function(index,obj){
			removeValidate(obj);
		});
	}
	if($('isSetMultiSkus').value == 1){
		$j('select[name^="skuOption"]').each(function(index,obj){
			if(!obj.disabled){
				applyValidate(obj,"required");
			}
		});
	}
	
	$j('input[name="itemQuantitys"]').each(function(index,obj){
		applyValidate(obj,"required,intRange=[1-100000]");
	});
	$j('input[name="listPrices"]').each(function(index,obj){
		applyValidate(obj,"price");
	});
	$j('input[name="prices"]').each(function(index,obj){
		applyValidate(obj,"price,required");
	});
	$j('input[name="salePrices"]').each(function(index,obj){
		applyValidate(obj,"price");
	});
	$j('input[name="weights"]').each(function(index,obj){
		applyValidate(obj,"floatRange=[0-100000]");
	});
	
	$j('input[name="wpPrices"]').each(function(index,obj){
		applyValidate(obj,"price,required");
	});
	$j('input[name="wpMinQuantitys"]').each(function(index,obj){
		if(flag){
			if("" == obj.value.trim() || !isNotNegativeInteger(obj.value.trim())){
				problemQuantity = obj;
				setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
				jAlert(__FMT.productForm_signNotNegativeNum);
				selectTab(0);
				flag = false;
			}
		}
	});
	$j('input[name="wpMaxQuantitys"]').each(function(index,obj){
		if(flag){
			if("" == obj.value.trim() || !isNotNegativeInteger(obj.value.trim())){
				problemQuantity = obj;
				setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
				jAlert(__FMT.productForm_signNotNegativeNum);
				selectTab(0);
				flag = false;
			}
		}
	});
	$j('input[name="wpMaxQuantitys"]').each(function(index,obj){
		if(flag){
			var maxQuantity= obj.value;
			var temp = $j(obj).parent("td:first");
			var temp2 = $j(obj).parent("td:first").prev();
			var minQuantity= $j(obj).parent("td:first").prev().children(".minQuantity").get(0).value;
			if(!isLargerEqual(maxQuantity,minQuantity)){
				problemQuantity = obj;
				setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
				jAlert(__FMT.productForm_incorrectMaxQuantity);
				selectTab(0);
				flag = false;
				
			}
		}
	});
   

	//end:validate apply
	
	if(flag){
		 if(!validateProduct($j("#productForm")[0])){
	    	focusOnInvalidTab();
	    	flag = false;
	   	}
   	}
  
   	return flag;
}

//保存产品 actionCode=0表示保存商品,=1表示保存商品并返回列表，=2表示保存商品并添加类似
function saveProduct(actionCode){
	if(!isLoadImagesSuccess){
		jAlert(__FMT.productForm_waitImagesLoaded);
		return false;
	}
	if(!isLoadSkusSuccess){
		jAlert(__FMT.productForm_waitSkusLoaded);
		return false;
	}
	if(!isLoadAttributesSuccess){
		jAlert(__FMT.productForm_waitAttributesLoaded);
		return false;
	}
	if(!isLoadRecommendsSuccess){
		jAlert(__FMT.productForm_waitRecommendsLoaded);
		return false;
	}
	
	if(!validateAction()){
    	return ;
    }
    var postData="";
    postData += $j('#productForm :input').serialize();
    var url=$j('#productForm').attr('action')+"?doAction=save";
    
    var callbackFunc = null;
    if(actionCode == 0){
    	callbackFunc = saveProductCallback;
    }else if(actionCode == 1){
    	callbackFunc = saveProductAndReturnCallback;
    }else if(actionCode == 2){
    	callbackFunc = saveProductAndAddSimilarCallback;
    }
	disableIconBtn("delete");
    $j.post(url,postData,callbackFunc,"json");
}
//保存商品回调
function saveProductCallback(data){
	if(data.error && data.error!=""){
		jAlert(data.error);
		return ;
	}
	enableIconBtn("delete");
	sysMsg("["+data.productName+"]"+__FMT.productForm_saveProduct_success);
	saveProductCallbackBase(data);
}

//保存商品并返回回调
function saveProductAndReturnCallback(data){
	if(data.error && data.error!=""){
		jAlert(data.error);
		return ;
	}

	saveProductCallbackBase(data);
	returnToList();
	sysMsg("["+data.productName+"]"+__FMT.productForm_saveProduct_success);
}

//保存商品并添加类似商品回调
function saveProductAndAddSimilarCallback(data){
	if(data.error && data.error!=""){
		jAlert(data.error);
		return ;
	}

	sysMsg("["+data.productName+"]"+__FMT.productForm_saveProduct_success);
	saveProductCallbackBase(data);
	disableIconBtn("delete");
	resetFieldForAddSimilar();
	
}
//为添加类似商品更新field
function resetFieldForAddSimilar(){
	initVariablesForAddSimilar();
	
	$j("#productId").val("");
	$j("#productName").val("");
	$j("#productCode").val("");
	
	$j('input[name="skuCodes"]').each(function(i,o){
		o.value = "";
	});
	
	$j('input[name="mediaIds"]').each(function(i,o){
		mediaId++;
		o.id = "mediaId_new_"+mediaId;
		o.value = "mediaId_new_"+mediaId;
	});
	$j('input[name="skuIds"]').each(function(i,o){
		skuCounter++;
		o.id = "skuId_new_"+skuCounter;
		o.value = "skuId_new_"+skuCounter;
		
		$j(o).parents(".content").find('input[name="wpSkuIds"]').each(function(j,w){
			w.id = "wpskuId_new_"+skuCounter;		
			w.value = "wpskuId_new_"+skuCounter;		
		});
		$j(o).parents(".content").find('input[name="wpIds"]').each(function(j,w){
			wholesalePriceCounter++;
			w.id = "wpIdnew_"+wholesalePriceCounter;		
			w.value = "wpIdnew_"+wholesalePriceCounter;		
		});
		
	});
	
}

//基本：保存产品回调函数
function saveProductCallbackBase(data){
	
	if(data.productId){
		$j("#productId").val(data.productId);
	}
	if(data.productCode){
		$j("#productCode").val(data.productCode);
	}
	if(data.skuCodes){
		$j('input[name="skuCodes"]').each(function(i,o){
			o.value = data.skuCodes[i];
		});
	}
	
	if (data.newMediaIds) {
		for (var i = 0; i < data.newMediaIds.length; i++) {
			$j("#" + data.oldMediaIds[i]).val("mediaId_"+data.newMediaIds[i]);
			$j("#" + data.oldMediaIds[i]).attr("id","mediaId_"+data.newMediaIds[i]);
		}
	}
	if (data.newSkuIds) {
		for (var i = 0; i < data.newSkuIds.length; i++) {
			$j("#" + data.oldSkuIds[i]).val("skuId_"+data.newSkuIds[i]);
			$j("#" + data.oldSkuIds[i]).attr("id","skuId_"+data.newSkuIds[i]);
		}
	}
	
	if (data.newWpIds) {
		for (var i = 0; i < data.newWpIds.length; i++) {
			$j("#" + data.oldWpIds[i]).val("wpId_"+data.newWpIds[i]);
			$j("#" + data.oldWpIds[i]).attr("id","wpId_"+data.newWpIds[i]);
		}
	}
	if (data.newWpSkuIds) {
		for (var i = 0; i < data.newWpSkuIds.length; i++) {
			$j("#" + data.oldWpSkuIds[i]).val("wpskuId_"+data.newWpSkuIds[i]);
			$j("#" + data.oldWpSkuIds[i]).attr("id","wpskuId_"+data.newWpSkuIds[i]);
		}
	}
	
	displayButtons(data.status);
	$j('#productStepInfo').html('<b>'+__FMT.productForm_stepLast+'</b></br>'); //清空步骤提示信息
	refreshParent();
}

// 删除当前编辑的产品
function deleteProduct(){
	var entityName = $j("#productName").val();
	if(confirm( __FMT.common_message_confirmDeleteThis+ "\"" + entityName+"\""+__FMT.productList_message_confirmDeleteThisSuffix)){
		var paraData = {
			productId: $j("#productId").val()
		};
		$j.post(__ctxPath + "/product/prod/blank.html?doAction=delete", paraData, deleteProductCallback,"json");
		
	}
}
//选择类型后的回调函数
function selectProductTypeCallback(productTypeId,productCategoryId){
	var url =  __ctxPath + "/product/prod/ajaxPage.html?doAction=edit&direct=false&productTypeId="+productTypeId;
	if($j('#package').val() != ""){
		url += "&package=true";
	}
	if(null != productCategoryId){
		url += "&productCategoryId="+productCategoryId;
	}
	showProductForm(url);
}

//删除后的回调函数
function deleteProductCallback(data){
	
	if(data.deleteInfos){
		var deleteInfo = data.deleteInfos[0];
		if(deleteInfo.deleteStatus == 0){
			//case:有正在进行中的订单，删除失败
			sysMsg(__FMT.product_label + deleteInfo.productName +__FMT.product_delete_false,true);			
		}else{
			//case:删除成功
			returnToList();
			sysMsg("'"+deleteInfo.productName+"'"+__FMT.product_delete_success);
			refreshParent();
		}
	
	}
	
	

}


//判断str1是否大于str2, str1和str2都是字符串值
function isLargerEqual(str1,str2){
	return parseInt(str1)>=parseInt(str2);
}	
//是否非负整数 str是一个字符串值
function isNotNegativeInteger(str){
	var regExp = new RegExp("^(([1-9][0-9]*)|0)$");
	return regExp.test(str);
}


//改变到按规格定价 即允许多个sku
// tableDivId 是sku所对应的skuTable
function changeToMultiSkus(tableDivId){
	if($j('input[name="skuOptionCheckbox"]').size() < 1){
		jAlert(__FMT.productForm_skuOptionCannotOpen);
		return;
	}
	$j('.content','#'+tableDivId).removeClass('no_sku');
	$j('#changeToMultiSkusBar').hide();
	$j('#addSkuBar').show();
	$('isSetMultiSkus').value = 1;
	
	
	
}
//改变到单sku
// tableDivId 是sku所对应的skuTable
function changeToSingleSku(tableDivId){
	$j('img[id^="skuImage"]','#'+tableDivId).get(0).src = __defaultImage; //清空图片
	$j('input[name="skuImageUrls"]').val("");//清空图片input
	closeSkuOptions(); //关闭所有规格
	
	$j('.content','#'+tableDivId).addClass('no_sku');
	$j('#changeToMultiSkusBar').show();
	$j('#addSkuBar').hide();
	$('isSetMultiSkus').value = 0;
	
}
//开启规格
function openSkuOptions(){
	//开启所有规格
	$j('input[name="skuOptionCheckbox"]').each(function(i,o){
		if(!o.checked){
			o.checked = true;
			toggleSkuOption(o,false);
		}
	});
	
	
	reConfigOptionIds();
}

//关闭规格
function closeSkuOptions(){
	//关闭所有规格
	$j('input[name="skuOptionCheckbox"]').each(function(i,o){
		if(o.checked){
			o.checked = false;
			toggleSkuOption(o,false);
		}
	});
}
//改变截止购买数量的handler
function wpMaxQuantityHandler(id){
	var obj = $j('.maxQuantity:last','#wholesalePrice'+id);
	if(!isNotNegativeInteger(obj.val())){
		jAlert(__FMT.productForm_signNotNegativeNum);
		obj.val("");
		problemQuantity = obj.get(0);
		setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住

	}else{
		var nextMinQuantity =obj.parent("td").parent("tr").next().find('.minQuantity');
		if(nextMinQuantity.size()!=0){
			nextMinQuantity.val(parseInt(obj.val())+1);
			nextMinQuantity.prev("span").html(nextMinQuantity.val());
		}
	}
}

//改变起始购买数量的handler
function wpMinQuantityHandler(id){
	var obj = $j('.minQuantity:last','#wholesalePrice'+id);
	if(!isNotNegativeInteger(obj.val())){
		jAlert(__FMT.productForm_signNotNegativeNum);
		obj.val("");
		problemQuantity = obj.get(0);
		setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
	}else{
	}
}
//新增sku，与Method：addSku区别在于它会增加一个默认的wholesalePrice
function newSku(tableDivId){
	var wholesalePriceTableId = addSku(tableDivId,null);
}
//增加sku
// tableDivId 是product所对应的skuTable
// sku 是一个JSON对象{id,code,imageUrl}

function addSku(tableDivId,sku){
	var id,code,mediaUrl,src;
	var listPrice,price,salePrice,weight,inventory;
	var optionValueInfo;
	var allocatedQuantity="0";
	if(null == sku){
		skuCounter++;
		id = "new_"+skuCounter;//包含表示新增
		code = "";
		mediaUrl=__defaultImage_m0;
		src =__defaultImage_m0;
		listPrice = "";
		price = "";
		salePrice = "";
		weight = "";
		inventory = "";
		optionValueInfo = "";
		allocatedQuantity = "0";
		
	}else{
		id = "_"+sku.id;
		code = sku.code;
		mediaUrl = sku.imageUrl;
		src = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s1"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
		listPrice = sku.listPrice;
		price = sku.price;
		salePrice =  sku.salePrice;
		weight =  sku.weight;
		inventory =  sku.inventory;
		optionValueInfo = sku.optionValueInfo;
		allocatedQuantity = sku.allocatedQuantity;
	}
	var html="";
	html += '<div class="content" id="sku'+id+'">';
	html += '<div class="circle_corner_block1"><div class="circle_corner_block2"><div class="circle_corner_block3"><div class="cnt">';
	//---start：操作区---
	html += '<div class="do">';
	html += '<a class="copy" href="javascript:void(0)" onclick="copySku(\''+tableDivId+'\',\'sku'+id+'\')" ></a>';
	html += '<a class="del" href="javascript:void(0)" onclick="delSku(\''+tableDivId+'\',\'sku'+id+'\')" ></a>';
	html += '</div>';
	//---end：  操作区---
	
	html += '<table class="sku_table_wrap"><tr>';
	//---start：概况区---
	html += '<td class="multiSku" valign="top">';
	html += '<table class="sku_table">';
	html += '<tr>';
	//---start：规格项选择区---
	html += '<td valign="top"><div class="sku">';
	
	html += '<ul class="now">';
	for(var i =0; i< skuOptionArray.length; i++){
		var skuOption = skuOptionArray[i];
		var isDisabled = (optionIds.indexOf(","+skuOption.id+",") != -1)?false:true;
		html += '<li class="skuOptionValueLi" '+(isDisabled?'style="display:none;"':'')+'>';
		//---start：目前选择区---
		html += '<em>';
		var isSelected = false;
		for(var j=0; j<skuOptionValueArray[i].length; j++){
			var skuOptionValue = skuOptionValueArray[i][j];
			
			isSelected = (optionValueInfo.indexOf(":"+skuOptionValue.id +";") != -1)?true:false;
			if(isSelected){
				html += getSelectedOptionValueDiv(skuOptionValue); 
				break;
			}
		}
		if(!isSelected){
			html += '<b class="default" title="'+__FMT.form_select_all+'"></b>';
		}
		html += '</em>';
		//---end：目前选择区---
		html += skuOption.name;
		//---start：候选区---
		html += '<ul class="option clearfix">';
		for(var j=0; j<skuOptionValueArray[i].length; j++){
			var skuOptionValue = skuOptionValueArray[i][j];
			var isSelected = (optionValueInfo.indexOf(":"+skuOptionValue.id +";") != -1)?true:false;
			if(skuOptionValue.type == 1){
				html += '<li class="txt '+(isSelected?'curr':'')+'" title="'+skuOptionValue.name+'">';
				html += '<a href="javascript:void(0)" optionId="'+skuOptionValue.optionId+'" optionValueId="'+skuOptionValue.id+'"  onclick="selectSkuOptionValue(this,'+i+','+j+');return false;">'+skuOptionValue.value+'</a>';
				if(isSelected){html+='<i></i>';};
				html += '</li>';
				if(isSelected){html+='<i></i>';};
			}else if(skuOptionValue.type == 2){
				html += '<li class="img '+(isSelected?'curr':'')+'" title="'+skuOptionValue.name+'">';
				html += '<a href="javascript:void(0)" optionId="'+skuOptionValue.optionId+'" optionValueId="'+skuOptionValue.id+'"  onclick="selectSkuOptionValue(this,'+i+','+j+');return false;" style="background-color:#'+skuOptionValue.value+'"></a>';
				if(isSelected){html+='<i></i>';};
				html += '</li>';
				
			}else if(skuOptionValue.type == 3){
				html += '<li class="img '+(isSelected?'curr':'')+'" title="'+skuOptionValue.name+'">';
				html += '<a href="javascript:void(0)" optionId="'+skuOptionValue.optionId+'" optionValueId="'+skuOptionValue.id+'"  onclick="selectSkuOptionValue(this,'+i+','+j+');return false;" style="background-image:url('+__mediaPath+skuOptionValue.value+')" title="'+skuOptionValue.name+'"></a>';
				if(isSelected){html+='<i></i>';};
				html += '</li>';
			}else{}
			
				
		}
		if(skuOptionValueArray[i].length == 0){
			//无候选规格值，提示
			html += '&nbsp;&nbsp;'+__FMT.productForm_noOptionalSkuOptionValue1+'&nbsp;<a href="javascript:void(0)" onclick="defineNewSkuOptionValue('+skuOption.id+')">';
			html += __FMT.productForm_noOptionalSkuOptionValue2+'</a>'+'&nbsp;'+__FMT.productForm_noOptionalSkuOptionValue3+'&nbsp;&nbsp;';
		}
		html += '</ul>';
		//---end：候选区---
		//---start：规格hidden区---
		html += '<span class="skuOption'+skuOption.id+'" >';
		html += '<select id="skuOption_'+id+'_'+i+'" name="skuOption'+skuOption.id+'" '+(isDisabled?'disabled':'')+' style="display:none;">';
			html += '<option value="">select</option>';
			for(var j=0; j<skuOptionValueArray[i].length; j++){
				var skuOptionValue = skuOptionValueArray[i][j];
				var isSelected = (optionValueInfo.indexOf(":"+skuOptionValue.id +";") != -1)?true:false;
				html += '<option value="'+skuOptionValue.id+'"'+(isSelected?'selected':'')+'>';
				html += skuOptionValue.name;
				html += '</option>';			
			}
		html += '</select>'
		html += '</span>';
		//---end：规格hidden区---
		html += '</li>';
		
	}
	html += '</ul>';
	
	html += '</div></td>';
	//---end：  规格项选择区---
	
	//---start：单品图片区---
	html += '<td valign="top"><div class="img_wrap">';
	if(mediaUrl==""){
		html += '<a href="javascript:void(0)">';
	}else{
		html += '<a href="'+__mediaPath +mediaUrl+'" target="_blank">';
	}
	html += '<img id="skuImage'+id+'" src="' + src+ '" width="115" height="115" onerror="this.src=__defaultImage_m0;this.onerror=\'\'" />';
	html += '</a>';
	html += '</div>';
	html += __FMT.productSku_image_tip+":"+__FMT.product_imageUrl_tip;
	html += '</td>';
	//---end：  单品图片区---
	
	html += '</tr>';
	
	//---start：上传图片按钮区---
	html += '<tr><td></td>';
	html += '<td><input type="hidden" name="skuImageUrls" id="skuImageUrl'+id+'" value="'+((null != sku)?sku.imageUrl:'')+'"></td></tr>';
	//---end：  上传图片按钮区---
	
	html += '</table>';
	html += '</td>';
	//---end：  概况区---
	
	//---start：销售区---
	html += '<td valign="top">';
	html += '<ul id="accordion'+id+'" style="width:450px;">';
	
	//---start：基本销售信息
	html += '<li> <h3>'+__FMT.productForm_basicPrice+'</h3> <table class="normal_table1">';
	html += '<tr>';
	html += '<th>'+__FMT.productSku_listPrice+':</th><td><input type="text" id="listPrice'+id+'" name="listPrices" value="'+listPrice+'"  class="inputtxt" style="width:120px;"/></td>';
	html += '<th>'+__FMT.productSku_productSkuCode+':</th><td><input id="skuCode'+id+'" name="skuCodes" value="'+code+'" class="inputtxt" style="width:120px"/></td>';
	html += '</tr>';
	html += '<tr>';
	html += '<th>'+__FMT.productSku_price+'(<span class="red">*</span>):</th><td><input type="text" id="price'+id+'"  name="prices" value="'+price+'" class="inputtxt" style="width:120px;"/></td>';
	html += '<th style="display:none;">'+__FMT.productSku_inventory+':</th><td style="display:none;"><input type="text"  id="inventory'+id+'" name="inventorys" value="'+inventory+'" class="inputtxt" style="width:120px;"/><input type="hidden"  id="inventory'+id+'_allocatedQ" name="inventory_allocatedQ" value="'+allocatedQuantity+'" class="inputtxt" style="width:120px;"/></td>';
	html += '</tr>';
	html += '<tr>';
	html += '<th>'+__FMT.productSku_salePrice+':</th><td><input type="text"  id="salePrice'+id+'" name="salePrices" value="'+salePrice+'" class="inputtxt" style="width:120px;"/></td>';
	html += '<th>'+__FMT.productSku_weight+':</th><td><input type="text" id="weight'+id+'"  name="weights" value="'+weight+'" class="inputtxt" style="width:120px;"/>('+weightUnit+')</td>';
	html += '</tr>';
	html += '</table ></li>';
	//---end：基本销售信息
	
	
	//批发价开始
	html += '<li> <h3>'+__FMT.productForm_wholesalePrice+'</h3> <div class="list_price">';
	html += '<table  class="normal_table2">';
	html += '<th>'+__FMT.wholesalePrice_minQuantity+'</th>';
	html += '<th>'+__FMT.wholesalePrice_maxQuantity+'</th>';
	html += '<th>'+__FMT.wholesalePrice_price+'</th>';
	html += '<th>'+__FMT.wholesalePrice_delete+'</th>';
	html += '</table>';
	html += '<div class="price_wrap"><table class="normal_table3" id="wholesalePriceTable'+id+'"></table></div>';
	html += '<div class="add_wrap"><a class="add_price" href="javascript:void(0)" onclick="addWholesalePrice(\'wholesalePriceTable'+id+'\',null)"></a></div>';
	html += '</div></li>';
	//批发价结束
	
	html += '</ul>';
	html += '</td>';
	//---end：  销售区---
	
	html += '</tr></table>';
	
	
	html += '</div></div></div></div>';
	//start:hidden
	html += '<input type="hidden" name="skuIds" value="skuId'+id+'" id="skuId'+id+'"/>';
	//end:hidden
	
	html += '</div>';
	$j('#'+tableDivId).append(html);
	
	
	initUpload("skuImageUrl" + id, "product", "jpg", "", uploadSkuImageCallback);
	//$j("#accordion"+id).accordion({header:"h3",animated:false});
	//使用定时器方式来加载 增加速度
	masterSetTimeout(initAccordion,20,id);
	$j('#sku'+id).find('.skuOptionValueLi').bind('mouseover',function(){$j(this).find('ul').show();}).bind('mouseout',function(){$j(this).find('ul').hide();});
	
	return "wholesalePriceTable"+id;
}

//初始化accordion
function initAccordion(id){
	$j("#accordion"+id).accordion({header:"h3",animated:false});
}

//选择了规格值 alinkDOM是选择规格值的a DOM; i和j是skuOptionValueArray的坐标值，通过调用skuOptionValueArray[i][j]获得值，其值是一个json对象{id,name,value,type}
function selectSkuOptionValue(alinkDOM,i,j){
	//start:表现层
	$j(alinkDOM).parent("li").addClass("curr").append("<i></i>");
	$j(alinkDOM).parent("li").siblings().removeClass("curr").find("i").remove();
	$j(alinkDOM).parent("li").parent("ul").hide();
	
	var currDiv = $j(alinkDOM).parents(".skuOptionValueLi").find("em");//目前选择的规格值区域
	currDiv.find("b").remove();
	currDiv.append(getSelectedOptionValueDiv(skuOptionValueArray[i][j]));
	//end:表现层
	
	//start:实际数据层
	var skuOption = skuOptionArray[i];
	
	var selectDOM = $j(alinkDOM).parents('.skuOptionValueLi').find('select[name^="skuOption"]').get(0);
	selectDOM.selectedIndex = j+1;//+1是因为表现层没有请选择的选项
	removeValidateNotPassTip(selectDOM);
	//end:实际数据层
	
}
//设置已选择的规格值区 skuOptionValue是一个json对象{id,name,value,type}
function getSelectedOptionValueDiv(skuOptionValue){
	html = "";
	if(skuOptionValue.type == 1){
		html += '<b class="txt" title="'+skuOptionValue.name+'">';
		html += skuOptionValue.value;
		html += '</b>';
	}else if(skuOptionValue.type == 2){
		html += '<b style="background-color:#'+skuOptionValue.value+'" title="'+skuOptionValue.name+'">';
		html += '</b>';
		
	}else if(skuOptionValue.type == 3){
		html += '<b style="background-image:url('+__mediaPath+skuOptionValue.value+')" title="'+skuOptionValue.name+'">';
		html += '</b>';
	}else{}
	return html;
}

//复制sku
// tableDivId 是sku所对应的skuTable;
// trDivId 是sku所对应的skuTr;
function copySku(tableDivId,trDivId,optionValueInfo){
	var id,code,src;
	var listPrice,price,salePrice,weight,inventory;
	if(null == optionValueInfo)optionValueInfo="";
	skuCounter++;
	id = "new_"+skuCounter;//包含表示新增
	listPrice = $j('input[name="listPrices"]','#'+trDivId).get(0).value;
	price = $j('input[name="prices"]','#'+trDivId).get(0).value;
	salePrice = $j('input[name="salePrices"]','#'+trDivId).get(0).value;
	weight = $j('input[name="weights"]','#'+trDivId).get(0).value;
	inventory = $j('input[name="inventorys"]','#'+trDivId).get(0).value;
	
	var wholesalePriceTableId = addSku("skuTable",{"id":id,"code":"","imageUrl":"","listPrice":listPrice,"price":price,"salePrice":salePrice,"weight":weight,"inventory":inventory,"optionValueInfo":optionValueInfo});
	
	var wpMinQuantitys = $j.map($j('input[name="wpMinQuantitys"]','#'+trDivId),function(o){return o.value;});
	var wpMaxQuantitys = $j.map($j('input[name="wpMaxQuantitys"]','#'+trDivId),function(o){return o.value;});
	var wpPrices = $j.map($j('input[name="wpPrices"]','#'+trDivId),function(o){return o.value;});
	for(var i = 0; i< wpMinQuantitys.length; i++){
		wholesalePriceCounter++;
		wholesalePriceId = "new_"+wholesalePriceCounter; //new前缀表示新增
		addWholesalePrice(wholesalePriceTableId,{"wpId":wholesalePriceId,"wpSkuId":id,"wpMinQuantity":wpMinQuantitys[i],"wpMaxQuantity":wpMaxQuantitys[i],"wpPrice":wpPrices[i],"wpDeliveryDay":""},i==0);
	}	
	
}
//上传SKU图片成功后的回调函数
function uploadSkuImageCallback(mediaUrl, fileInputId){
	var src_s1 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s1"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	$j("#" + fileInputId.replace("Url","")).get(0).src = src_s1;
	$j("#" + fileInputId.replace("Url","")).parent('a').attr("href",__mediaPath+mediaUrl).attr("target","_blank");
}
//删除SKU图片函数
function deleteSkuImage(fileInputId){
	$j("#"+fileInputId).val("");
	$j("#" + fileInputId.replace("Url","")).get(0).src = __defaultImage_m0;
}
//删除sku
// tableDivId 是sku所对应的skuTable;
// trDivId 是sku所对应的skuTr;
function delSku(tableDivId,trDivId){
	var size = $j('.content','#'+tableDivId).size();
	
	if(size > 1){
		if(trDivId.indexOf("new") == -1 ){
			//检查是否能删除“旧”sku
			var paraData = {
				productSkuId: trDivId.substring("sku_".length)
			};
			$j.post(__ctxPath + "/product/prod/blank.html?doAction=checkSkuIsInUse", paraData, checkSkuIsInUseCallback,"json");
		}else{
			//删除“新”sku
			$j('#'+trDivId).remove();
		}
	}else{
		changeToSingleSku(tableDivId);
	}	
}

//检查sku是否被订单使用
function checkSkuIsInUseCallback(data){
	
	if(data.result){
		//正在被使用，不可以删除
		jAlert(__FMT.productForm_skuIsInUse);
	}else{
		$j('#sku_'+data.productSkuId).remove();
	}	
}


//增加批发价
// tableDivId 是批发价所对应的wholesalePriceTable;
// wholesalePrice是一个JSON对象{wpId,wpSkuId,wpMinQuantity,wpMaxQuantity,wpPrice,wpDeliveryDay};
function addWholesalePrice(tableDivId,wholesalePrice){
	
	var id,skuId,minQuantity,maxQuantity,price,deliveryDay;
	var isFirst = true;
	var lastMaxQuantity = $j('.maxQuantity:last','#'+tableDivId);
	if(lastMaxQuantity.size() == 0){
		isFirst = true;
	}else{
		isFirst = false;
	}
	if(null == wholesalePrice){
		wholesalePriceCounter++;
		id = "new_"+wholesalePriceCounter; //new前缀表示新增
		
		
		if(!isFirst){
			//start:获得上一个最大值,并设置下一个最小值
			if(null != lastMaxQuantity && lastMaxQuantity.val()!= "" ){
				if(isNotNegativeInteger(lastMaxQuantity.val())){
					minQuantity = ""+(parseInt(lastMaxQuantity.val())+1);
				}else{
					jAlert(__FMT.productForm_signNotNegativeNum);
					lastMaxQuantity.get(0).focus();
				return;
				}	
			}else{
				jAlert(__FMT.productForm_signLastMaxQuantity);
				lastMaxQuantity.get(0).focus();
				return;
			}	
			//end:获得上一个最大值,并设置下一个最小值
			
		}else{
			minQuantity = "1";
		}	
		maxQuantity = "";
		price = "";
		deliveryDay = "";
	}else{
		id = "_"+wholesalePrice.wpId;
		minQuantity = wholesalePrice.wpMinQuantity;
		maxQuantity = wholesalePrice.wpMaxQuantity;
		price = wholesalePrice.wpPrice;
		deliveryDay = wholesalePrice.wpDeliveryDay;
	}
	var skuTr = $j('#'+tableDivId).parents(".content");
	var skuIdInput = $j('input[name="skuIds"]',skuTr);
	skuId = "wp"+skuIdInput.val();
	//将上一个的delete 链接隐藏
	var lastDelete = $j('a.deleteWholesalePrice:last','#'+tableDivId);
	lastDelete.hide();
	
	var html = "";
	html += '<tr id="wholesalePrice'+id+'" >';
	if(isFirst){
		html += '<td ><input style="width:100px;" class="minQuantity inputtxt" id="wpMinQuantity'+id+'"  name="wpMinQuantitys" value="'+minQuantity+'" onchange="wpMinQuantityHandler(\''+id+'\')"/></td>';
	}else{
		html += '<td ><span>'+minQuantity+'</span><input type="hidden" class="minQuantity" id="wpMinQuantity'+id+'" name="wpMinQuantitys" value="'+minQuantity+'"/></td>';
	}
	html += '<td ><input style="width:100px;" class="maxQuantity inputtxt" id="wpMaxQuantity'+id+'" name="wpMaxQuantitys" value="'+maxQuantity+'"  onchange="wpMaxQuantityHandler(\''+id+'\')"/></td>';
	html += '<td ><input style="width:100px;" class="inputtxt" id="wpPrice'+id+'" name="wpPrices" value="'+price+'"/></td>';
	html += '<td ><a class="deleteWholesalePrice del_price" href="javascript:void(0)" onclick="delWholesalePrice(\''+tableDivId+'\',\'wholesalePrice'+id+'\')" ><b>&nbsp;</b></a></td>';
	//start:hidden
	html += '<input type="hidden" name="wpIds" id="wpId'+id+'" value="wpId'+id+'"/>';
	html += '<input type="hidden" name="wpSkuIds" id="'+skuId+'" value="'+skuId+'"/>';
	//end:hidden
	html += '</tr>';
	$j('#'+tableDivId).append(html); 
	
}
//删除批发价
// tableDivId 是批发价所对应的wholesalePriceTable;
// trDivId 是批发价所对应的wholesalePriceTr;
function delWholesalePrice(tableDivId,trDivId){
	$j('#'+trDivId).remove();
	//将上一个的delete 链接显示
    var lastDelete = $j('.deleteWholesalePrice:last','#'+tableDivId);
    lastDelete.show();
}
//切换规格可用与不可用
//checkboxDOM是一个规格的checkbox DOM
//isNeedWarning 是否需要提示信息 tru需要 false不需要
function toggleSkuOption(checkboxDOM,isNeedWarning){
	var jOptionInput = $j(checkboxDOM).next('[name="selectedOptions"]');
	var optionId = jOptionInput.get(0).value;
	var jSelect = $j('select[name="skuOption'+optionId+'"]');
	
	if(checkboxDOM.checked){
		jOptionInput.get(0).disabled = false;
		$j('.skuOption'+optionId,'#skuTable').show();
		jSelect.each(function(i,o){
			o.disabled = false;
		});
		jSelect.parents('.skuOptionValueLi').show();  //表现层show
		resetSelectedOptionValue(jSelect.parents('.skuOptionValueLi')); //重置已选择区表现层，候选区全都未选择
		
	}else{
		if(isNeedWarning){ //如果需要警告
			if($j('input[name="skuOptionCheckbox"]:checked').length == 0){
				//至少需要一个规格
				jAlert(__FMT.productForm_skuOptionAtLeastOne);
				checkboxDOM.checked=true;
			}else{
				jConfirm(__FMT.productForm_skuOptionDisable,"",function(flag){
					if(!flag){
						//撤销否选操作
						checkboxDOM.checked=true;
					}else{
						//确认否选操作
						jOptionInput.get(0).disabled = true;	
						$j('.skuOption'+optionId,'#skuTable').hide();
						jSelect.each(function(i,o){
							o.disabled = true;
							o.selectedIndex = 0;
						});
						jSelect.parents('.skuOptionValueLi').hide();  //表现层hidden
					}
					//重新修订optionIds值
					reConfigOptionIds();
				});
			}	
		}else{
			//确认否选操作
			jOptionInput.get(0).disabled = true;	
			$j('.skuOption'+optionId,'#skuTable').hide();
			jSelect.each(function(i,o){
				o.disabled = true;
				o.selectedIndex = 0;
			});
			jSelect.parents('.skuOptionValueLi').hide();  //表现层hidden
		}
	}
	reConfigOptionIds();
	
}

//重新修订optionIds值
function reConfigOptionIds(){
	optionIds = ",";
	$j('input[name="selectedOptions"]:enabled').each(function(i,o){
		optionIds += o.value + ",";
	});
	
}

//重置规格值选择区表现层 jSkuOptionValueLi是这个区域的jquery对象
function resetSelectedOptionValue(jSkuOptionValueLi){
	jSkuOptionValueLi.find('em').empty().append('<b class="default"></b>');
	jSkuOptionValueLi.find('ul li').removeClass("curr").find('i').remove();
}


//产品上架
function shelveProduct(){
	var postData = {"productId":$j("#productId").val()};
	var url=$j('#productForm').attr('action')+"?doAction=shelve";
    $j.post(url,postData,shelveProductCallback,"json");
}
//产品上架callback
function shelveProductCallback(data){
	displayButtons(data.status);
	refreshParent();
}
//产品手动下架
function offShelveProduct(){
	var postData = {"productId":$j("#productId").val()};
	var url=$j('#productForm').attr('action')+"?doAction=offShelve";
    $j.post(url,postData,offShelveProductCallback,"json");
}
//产品手动下架callback
function offShelveProductCallback(data){
	displayButtons(data.status);
	refreshParent();
}

//选择目录
function selectCategory(){
	showDialogOfproductCategorySelector();
}

//选择目录callback category 是一个json对象 {id，name}
function selectCategoryCallback(category){
	$j.getJSON(__ctxPath+"/product/prod/blank.html?doAction=getFullCategoryPathName&categoryId="+category.id,null,getFullCategoryPathNameCallback);
	$j('#categoryId').val(category.id);
	closeDialogOfproductCategorySelector();
	$j('#categoryId').next('img').remove();//如果有验证错误的移除
}
//根据名称获取目录全名
function getFullCategoryPathNameCallback(data){
	$j('#categoryName').html(data.fullCategoryPathName);
}

//显示自动评估商品
function showAutoEvalProducts(linkDOM,typeId){
	if($j("#productId").val() == ""){
		//case:商品未保存 则显示为“请先保存”
		$j('#autoEvalProductsDiv_'+typeId).empty().append(__FMT.productDetail_recommendResult_saveFirst);
	}else if($j('#autoEvalArea_'+typeId).html().indexOf("hasShow") == -1){
		//case:第一次展开
		$j('#autoEvalArea_'+typeId).append('<span class="hasShow"/>'); //增加一个显示标志
		var postData = {"productId":$j("#productId").val(),"recommendedTypeId":typeId};
		var url=$j('#productForm').attr('action')+"?doAction=getAutoEvalProducts";
		$j('#autoEvalProductsDiv_'+typeId).empty().loading();
	    $j.post(url,postData,showAutoEvalProductsCallback,"json");
	}else{
		//case:非第一次展开
	}   
	$j('#autoEvalCloseBtn_'+typeId).show();
	$j('#autoEvalShowBtn_'+typeId).hide();
	$j('#autoEvalArea_'+typeId).slideDown();
	$j(linkDOM).parents(".top:first").addClass("curr");
	
}

//重新评估
function reAutoEvalProducts(typeId){
	var postData = {"productId":$j("#productId").val(),"recommendedTypeId":typeId};
	var url=$j('#productForm').attr('action')+"?doAction=getAutoEvalProducts";
	$j('#autoEvalProductsDiv_'+typeId).empty().loading();
    $j.post(url,postData,showAutoEvalProductsCallback,"json");
}


//显示自动评估商品callback
function showAutoEvalProductsCallback(data){
	var typeId = data.recommendedTypeId;
	var products = data.autoEvalProductArray;
	$j('#autoEvalProductsDiv_'+typeId).empty();
	if(products.length > 0){
		for(var i=0; i< products.length; i++){
			addAutoEvalProduct("autoEvalProductsDiv_"+typeId,products[i],typeId);
		}
	}else{
		$j('#autoEvalProductsDiv_'+typeId).append(__FMT.productDetail_recommendResult_none);
	}	
	$j('#autoEvalCloseBtn_'+typeId).show();
	$j('#autoEvalShowBtn_'+typeId).hide();
	

}
//关闭自动评估显示
function closeAutoEvalProducts(linkDOM,typeId){
	$j('#autoEvalCloseBtn_'+typeId).hide();
	$j('#autoEvalShowBtn_'+typeId).show();
	$j('#autoEvalArea_'+typeId).slideUp();
	$j(linkDOM).parents(".top:first").removeClass("curr");
}



//添加自动评估商品
//divId 添加到的区域id； product 是一个json对象{product.id,product.name,product.imageUrl}; typeId推荐类型id
function addAutoEvalProduct(divId,product,typeId){
	var html = '<li>';
	html += '<span class="img"><img src="'+__mediaPath+product.imageUrl+'" width="115" height="115" onerror="this.src=__defaultImage;this.onerror=\'\'" /></img></span>';
	html += '<h4>'+product.name+'</h4>';
	html += '</li>';
	$j('#'+divId).append(html);
	
}

//手动添加商品
// product 是一个json对象{product.id,product.name,product.imageUrl}; typeId推荐类型id
function addManulProduct(product,typeId){
	recommendedProductCounter++;
	var mediaUrl = product.imageUrl;
	var src_s1 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s1"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	var html = '<td class="recommendedProduct'+typeId+'"><div class="img clearfix" id="recommendedProduct'+recommendedProductCounter+'">';
	html += '<a href="'+__mediaPath+product.imageUrl+'" target="_blank"><img src="'+src_s1+'" width="100" height="100" onerror="this.src=__defaultImage_s1;this.onerror=\'\'" /></img></a>';
	html += '<h4>'+product.name+'</h4>';
	html += '<div class="do">';
	html += '<a href="javascript:void(0)" onclick="moveUpRecommendedProduct(this,'+typeId+')" name="move_l" class="move_l"></a>';
	html += '<a href="javascript:void(0)" onclick="removeRecommendedProduct(this,'+typeId+')" class="del"></a>';
	html += '<a href="javascript:void(0)" onclick="moveDownRecommendedProduct(this,'+typeId+')" name="move_r" class="move_r"></a>';
	html += '</div>';
	//start:hidden
	html += '<input type="hidden" name="recommendedProductIds" value="'+product.id+'"/>';
	html += '<input type="hidden" name="recommendedTypeIds" value="'+typeId+'"/>';
	//end:hidden
	html += '</div></td>';
	$j('#manualProductsDiv_'+typeId).append(html);
	$j('#recommendedProduct'+recommendedProductCounter).bind('mouseover',function(){$j(this).find('.do').show();$j(this).addClass("curr");}).bind('mouseout',function(){$j(this).find('.do').hide();$j(this).removeClass("curr");});
	showRecommendedProductMoveIcons(typeId);
}


//删除附件 
//linkDOM 是一个超链接对象
function removeRecommendedProduct(linkDOM,typeId){
	if (confirm(__FMT.common_message_confirmDeleteThis +"?")) {
		$j(linkDOM).parents(".recommendedProduct"+typeId).remove();
		showRecommendedProductMoveIcons(typeId);
	}	
}


//提升推荐商品顺序
//linkDOM 是一个超链接对象
function moveUpRecommendedProduct(linkDOM,typeId){
	var me = $j(linkDOM).parents(".recommendedProduct"+typeId);
	var prev = me.prev(".recommendedProduct"+typeId);
	prev.before(me);
	showRecommendedProductMoveIcons(typeId);
}

//降低推荐商品顺序
//linkDOM 是一个超链接对象
function moveDownRecommendedProduct(linkDOM,typeId){
	var me = $j(linkDOM).parents(".recommendedProduct"+typeId);
	var next = me.next(".recommendedProduct"+typeId);
	next.after(me);
	showRecommendedProductMoveIcons(typeId);
}

//刷新图片区左移和右移图标是否显示
function showRecommendedProductMoveIcons(typeId){
	$j('#manualProductsDiv_'+typeId+' td.recommendedProduct'+typeId+' a[name="move_l"]').addClass("move_l").removeClass("move_l_gray");
	$j('#manualProductsDiv_'+typeId+' td.recommendedProduct'+typeId+' a[name="move_r"]').addClass("move_r").removeClass("move_r_gray");
	$j('#manualProductsDiv_'+typeId+' td.recommendedProduct'+typeId+':first a[name="move_l"]').addClass("move_l_gray").removeClass("move_l");
	$j('#manualProductsDiv_'+typeId+' td.recommendedProduct'+typeId+':last a[name="move_r"]').addClass("move_r_gray").removeClass("move_r");
}


//通过商品选择器选择推荐商品
function selectRecommendedProduct(typeId){
	currentTypeId = typeId;
	showDialogOfproductSelector();
}
//通过商品选择器选择推荐商品callback
function selectRecommendedProductCallback(productArray){
	var typeId = currentTypeId;
	closeDialogOfproductSelector();
	for(var i=0; i< productArray.length; i++)
	{
		var product = productArray[i];
		if($j('#manualProductsDiv_'+typeId).find('input[name="recommendedProductIds"][value="'+product.productId+'"]').length!=0){
			//不能添加重复元素
			jAlert(product.productName+'('+product.productCode+')'+__FMT.productForm_adddRecommended_noRepeat);
		}else if($j('#productId').val() == product.productId){
			//不能添加自身
			jAlert(product.productName+'('+product.productCode+')'+__FMT.productForm_adddRecommended_noSelf);
		}else{	
			//无重复和自我
			addManulProduct({"id":product.productId,"name":product.productName,"imageUrl":product.imageUrl},typeId);
		}	
	}
		
}
//清空所有关联商品
function removeAllRecommendedProduct(typeId){
	if (confirm(__FMT.common_message_confirmClear +"?")) {
		$j('#manualProductsDiv_'+typeId).empty();
	}	
}

//选择商品包内货品
function selectPackageProduct(){
	showDialogOfproductSkuSelector();		
}	
//选择商品包内货品的回调函数
function selectPackageProductCallback(productSkuArray){
	closeDialogOfproductSkuSelector();
	for(var i=0; i< productSkuArray.length; i++)
	{
		var productSku = productSkuArray[i];
		
		if($j('#productPackageList').find('input[name="itemSkuIds"][value="'+productSku.productSkuId+'"]').length!=0){
			//不能添加重复元素
			jAlert(productSku.productName+'('+productSku.productSkuCode+')'+__FMT.productForm_adddPackageItem_noRepeat);
		}else if($j('#productId').val() == productSku.productId){
			//不能添加自身
			jAlert(productSku.productName+'('+productSku.productCode+')'+__FMT.productForm_adddPackageItem_noSelf);
		}else if(productSku.productKind != 1){
			//不能再添加商品包
			jAlert(productSku.productName+'('+productSku.productCode+')'+__FMT.productForm_adddPackageItem_noPackage);
		}else{	
			//无重复和自我
			addPackageSku(productSku);
		}	
		
	}
}


//添加商品包内货品
//productSku是一个json对象(同货品选择器的回调值+quantity) ;needMoveIcons用于是否执行函数showPackageSkuMoveIcons，用于页面速度优化，默认需要
function addPackageSku(productSku,needMoveIcons){
	var mediaUrl = productSku.imageUrl;
	var quantity ;
	if(productSku.quantity == undefined){
		quantity = 1;
	}else{
		quantity = productSku.quantity;
	}	 
	var src_s1 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s1"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	if (!mediaUrl) {
		src_s1 = __mediaPath + productSku.productImageUrl;
	}
	var html = '<td class="packageSku"><div class="img clearfix" id="packageSku'+productSku.productSkuId+'">';
	html += '<a href="'+src_s1+'" target="_blank"><img src="'+src_s1+'" width="100" height="100" onerror="this.src=__defaultImage_s1;this.onerror=\'\'" /></img></a>';
	html += '<h4 title="'+productSku.productName+'('+productSku.productSkuCode+')">'+productSku.productName+'<br/>'+__FMT.productDetail_package_productSkuCode+':'+productSku.productSkuCode;
	html += '<br/>'+__FMT.productDetail_package_quantity+'(<span class="red">*</span>):<input type="text" class="inputtxt" style="width:50px;" name="itemQuantitys" id="itemQuantity'+productSku.productSkuId+'" value="'+quantity+'"/></h4>';
	html += '<div class="do">';
	html += '<a href="javascript:void(0)" onclick="moveUpPackageSku(this)" name="move_l" class="move_l"></a>';
	html += '<a href="javascript:void(0)" onclick="removePackageSku(this)" class="del"></a>';
	html += '<a href="javascript:void(0)" onclick="moveDownPackageSku(this)" name="move_r" class="move_r"></a>';
	html += '</div>';
	//start:hidden
	html += '<input type="hidden" name="itemSkuIds" id="itemSkuId'+productSku.productSkuId+'" value="'+productSku.productSkuId+'"/>';
	//end:hidden
	html += '</div></td>';
	$j('#productPackageList').append(html);
	$j('#packageSku'+productSku.productSkuId).bind('mouseover',function(){$j(this).find('.do').show();$j(this).addClass("curr");}).bind('mouseout',function(){$j(this).find('.do').hide();$j(this).removeClass("curr");});
	if(needMoveIcons == null || needMoveIcons){
		showPackageSkuMoveIcons();
	}
}

//清空所有关联商品
function removeAllPackageProduct(){
	if (confirm(__FMT.common_message_confirmClear +"?")) {
		$j('#productPackageList').empty();
	}	
}

//刷新图片区左移和右移图标是否显示
function showPackageSkuMoveIcons(){
	$j('#productPackageList td.packageSku a[name="move_l"]').addClass("move_l").removeClass("move_l_gray");
	$j('#productPackageList td.packageSku a[name="move_r"]').addClass("move_r").removeClass("move_r_gray");
	$j('#productPackageList td.packageSku:first a[name="move_l"]').addClass("move_l_gray").removeClass("move_l");
	$j('#productPackageList td.packageSku:last a[name="move_r"]').addClass("move_r_gray").removeClass("move_r");
}

//删除商品包内货品
//linkDOM 是一个超链接对象
function removePackageSku(linkDOM){
	if (confirm(__FMT.common_message_confirmDeleteThis +"?")) {
		$j(linkDOM).parents(".packageSku").remove();
		showPackageSkuMoveIcons();
	}	
}


//提升商品包内货品顺序
//linkDOM 是一个超链接对象
function moveUpPackageSku(linkDOM){
	var me = $j(linkDOM).parents(".packageSku");
	var prev = me.prev(".packageSku");
	prev.before(me);
	showPackageSkuMoveIcons();
}

//降低商品包内货品顺序
//linkDOM 是一个超链接对象
function moveDownPackageSku(linkDOM){
	var me = $j(linkDOM).parents(".packageSku");
	var next = me.next(".packageSku");
	next.after(me);
	showPackageSkuMoveIcons();
}

/**
 * 初始化upload控制
 * @param {Object} fileInputId 需上传的Input
 * @param {Object} uploadCategory 上传文件保存的目录
 * @param {Object} supportedSuffixs 支持的后缀，多个逗号隔开，空表示不限制
 * @param {Object} nonsupportedSuffixs不支持的后缀，多个逗号隔开，空表示不限制
 * @param {Object} onCompleteHandler 上传成功后的回调，返回来个参数，一个是上传后的文件路径，另一个是需上传的Input ID
 */
function initUpload(fileInputId, uploadCategory, supportedSuffixs, nonsupportedSuffixs, onCompleteHandler){
	var urlAction = '/dialog/upload.html?uploadCategory=' + uploadCategory + "&fileInputId=" + fileInputId;
	if (onCompleteHandler) 
		urlAction += "&onCompleteHandler=" + onCompleteHandler.toLocaleString().substring(9, onCompleteHandler.toLocaleString().indexOf("("));
	var plugin_upload_valid = true;
	$j("<input type='button' class='upload_img_2' />").insertAfter("#" + fileInputId).upload({
		name: 'file',
		action: __ctxPath + urlAction,
		enctype: 'multipart/form-data',
		params: {},
		onSubmit: function(){
			return plugin_upload_valid;
		},
		onComplete: function(){
		},
		onSelect: function(){
			plugin_upload_valid = true;
			var idx = this.filename().lastIndexOf(".");
			if (idx == -1 || idx >= this.filename().length) {
				plugin_upload_valid = false;
			}
			var suffix = this.filename().substring(idx + 1, this.filename().length).toLowerCase();
			if (plugin_upload_valid && supportedSuffixs) {
				plugin_upload_valid = (supportedSuffixs.toString().indexOf(suffix) >= 0);
			}
			if (plugin_upload_valid && nonsupportedSuffixs) {
				plugin_upload_valid = (nonsupportedSuffixs.toString().indexOf(suffix) == -1);
			}
			if (!plugin_upload_valid) {
				jAlert(__FMT.error_upload_unsupport + ":" + supportedSuffixs.toString());
				return false;
			}
		},
		autoSubmit: true
	});
	$j("#" + fileInputId).wrap("<div style='float:left;'></div>");
}

//移除验证不通过标志 inputDOM是需要移除的表单元素dom
function removeValidateNotPassTip(inputDOM){
	$j(inputDOM).removeClass("x-form-invalid");
	$j(inputDOM).next('img').remove();
}
//重新定义productType
function reDefineProductType(productTypeId){
	var url = __ctxPath+"/product/productType.html?doAction=edit&productTypeId="+productTypeId;
	if(confirm(__FMT.productForm_noOpenSkuOption_confirm)){
		window.location = url;
	}
}

//选择商品类型分页
function fnOnGoToPageSelectType(){
	var postData = $j('#productTypeListForm :input').serializeArray();
	var url=__ctxPath+"/product/prod/ajaxPage.html?&doAction=selectProductType";
	showSelectTypeForm(url,postData); 
}


//从productForm返回到list
function returnToList(){
	getCurrListHeight();
	$j('#formDiv').hide();
	$j('#mainDiv').show();
}

//刷新父窗口的产品列表
function refreshParent(){
	refreshProductList();
}
//定义新的规格值
function defineNewSkuOptionValue(skuOptionId){
	if(confirm(__FMT.productForm_confirmDefineAction)){
		window.location = __ctxPath+"/product/skuOption.html?doAction=edit&skuOptionId="+skuOptionId;
	}
}

//打开货品生成器对话框
function openGenSkusDialog(){
	if($j('input[name="skuOptionCheckbox"]').size() < 1){
		jAlert(__FMT.productForm_skuOptionCannotOpen);
		return;
	}
	dlgoptionValueChoies_show();
	
}

//生成多个货品
function genSkus(tableDivId){
	
	
	var tableDivId='skuTable';
	if($j('.choice li.curr').length==0){
		jAlert(__FMT.productForm_selectOptionValueAtLeast);
		return false;
	}
	//开启规格
	changeToMultiSkus(tableDivId);	
	//获得第一个货品div id
	var trDivId = $j('#'+tableDivId).find('div[id^="sku"]:first').attr("id");
	//先构造已选择的二维数组
	var skuOptionValueMultiArray = new Array();
	var digitMultiArray = new Array();
	$j('ul.choice').each(function(){
		var skuOptionValueSingleArray = new Array();
		var digitSingleArray = new Array();
		$j(this).find('li.curr').each(function(i,o){
			skuOptionValueSingleArray.push({optionId:$j(this).attr("optionId"),optionValueId:$j(this).attr("optionValueId")});
			digitSingleArray.push(i);
		});
		if(skuOptionValueSingleArray.length!=0){
			skuOptionValueMultiArray.push(skuOptionValueSingleArray);
			digitMultiArray.push(digitSingleArray);
			var optionCheckbox = $j('#skuOptionCheckbox_'+skuOptionValueSingleArray[0].optionId).get(0);
			optionCheckbox.checked = true;
			toggleSkuOption(optionCheckbox,false);//开启规格
		}
	});
	//计算排列(递归算法)
	var concatArray = digitMultiArray[0];
	if(digitMultiArray.length > 1){
		for(var m=1;m<digitMultiArray.length;m++){
			concatArray = arrayConcat(concatArray,digitMultiArray[m]);
		}
	}
	//生成货品
	for(var i=0;i<concatArray.length;i++){
		//生成规格选择值字符串
		var indexs = (concatArray[i]+"").split(",");
		var skuOptionValueInfo = "";
		for(var j=0;j<indexs.length;j++){
			skuOptionValueInfo+=skuOptionValueMultiArray[j][indexs[j]].optionId+":"+skuOptionValueMultiArray[j][indexs[j]].optionValueId+";";
		}
		if(i==0){
			for(var k=0;k<indexs.length;k++){
				var selectedOptionId = skuOptionValueMultiArray[k][indexs[k]].optionId;
				var selectedOptionValueId = skuOptionValueMultiArray[k][indexs[k]].optionValueId;
				$j('#'+trDivId+' ul.option a[optionId="'+selectedOptionId+'"][optionValueId="'+selectedOptionValueId+'"]').trigger('click');
			}
		}else{
			copySku(tableDivId,trDivId,skuOptionValueInfo);
		}	
	}
	//关闭货品生成选择器
	dlgoptionValueChoies_close();
	
	
}

//将两个数组 组合成 一个数组(数组值均为字符串)，例如[0,1]与[a,b]组合成[0,a][0,b][1,a][1,b]
function arrayConcat(array1,array2){
	var array = new Array();
	for(var i=0; i<array1.length; i++){
		for(var j=0; j<array2.length; j++){
			array.push(array1[i]+","+array2[j]);
		}
	}
	return array;
}

//货品生成器 选择了规格值 
function toggleGenDialogSkuOptionValue(event){
	if($j(this).hasClass("curr")){
		$j(this).removeClass("curr").find("i").remove();
	}else{
		$j(this).addClass("curr").append("<i></i>");
	}
}

//加载图片区域成功后的回调函数
function loadImagesCallback(){
	isLoadImagesSuccess = true;
	loadButtons();
}
//加载货品区域成功后的回调函数
function loadSkusCallback(){
	isLoadSkusSuccess = true;
	loadButtons();
}
//加载属性区域成功后的回调函数
function loadAttributesCallback(){
	isLoadAttributesSuccess = true;
	loadButtons();
}
//加载推荐商品区域成功后的回调函数
function loadRecommendsCallback(){
	isLoadRecommendsSuccess = true;
	loadButtons();
}
//加载显示按钮，必须等所有ajaxload的区域全部加载完成后display
function loadButtons(){
	if(isLoadImagesSuccess && isLoadSkusSuccess && isLoadAttributesSuccess && isLoadRecommendsSuccess){
		displayButtons(productStatus); //显示操作按钮
	}
}

